package com.aiyige.page.pay;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.eventbus.EventMomentChanged;
import com.aiyige.model.AiyigeExceptionModel;
import com.aiyige.model.Subject;
import com.aiyige.model.User;
import com.aiyige.model.eshop.Order;
import com.aiyige.model.eshop.OrderPay;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.model.pingxx.PingPayModel;
import com.aiyige.model.response.ErrorResponse;
import com.aiyige.page.my.order.myOrder.MyOrdersDataPage;
import com.aiyige.page.pay.model.OrderModel;
import com.aiyige.page.pay.model.PayResult;
import com.aiyige.page.pay.model.UnpayModel;
import com.aiyige.page.pay.util.PayUtil;
import com.aiyige.track.TrackEvent;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.crash.CrashUtils;
import com.aiyige.utils.dialog.LoadingDialog;
import com.aiyige.utils.widget.CommonTitleDetailDialog;
import com.aiyige.utils.widget.LabelImageView;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.pingplusplus.android.Pingpp;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

import static com.aiyige.page.pay.ConfirmOrderPage.CLASS_IS_STARTED;
import static com.aiyige.page.pay.ConfirmOrderPage.MOMENT_HAS_CHANGED;
import static com.aiyige.page.pay.ConfirmOrderPage.ORDER_GOODS_IS_EMPTY;
import static com.aiyige.page.pay.ConfirmOrderPage.REQUEST_CODE_CONFIRM_PAY;
import static com.aiyige.page.pay.ConfirmOrderPage.REQUEST_CODE_SELL_OUT;

@Route(path = ARouterConfig.ConfirmPayPage, extras = ARouterConfig.EXTRA_NEED_LOGIN)
public class ConfirmPayPage extends BaseActivity {
    public static final int REQUEST_CODE_PAY_RESULT = 1;
    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.titleTv)
    TextView titleTv;

    @BindView(R.id.iv_head)
    ImageView avatarIv;
    @BindView(R.id.tv_name)
    TextView userNameTv;


    @BindView(R.id.iv_cover)
    LabelImageView coverIv;
    @BindView(R.id.tv_title)
    TextView goodsTitleTv;
    //    @BindView(R.id.goodsTypeTv)
//    TextView goodsTypeTv;
    @BindView(R.id.tv_count)
    TextView goodsBuyNumTv;
    @BindView(R.id.tv_price)
    TextView singlePriceTv;
    @BindView(R.id.tv_lineation_price)
    TextView tvLineationPrice;
    @BindView(R.id.moneyTv)
    TextView moneyTv;
    @BindView(R.id.wechatIv)
    ImageView wechatIv;
    @BindView(R.id.wechatMethodIv)
    ImageView wechatMethodIv;
    @BindView(R.id.alipayIv)
    ImageView alipayIv;
    @BindView(R.id.alipayMethodIv)
    ImageView alipayMethodIv;
    @BindView(R.id.balanceMethodIv)
    ImageView balanceMethodIv;

    @BindView(R.id.confirmTotalMoneyLabel)
    TextView confirmTotalMoneyLabel;
    @BindView(R.id.currencySymbolTv2)
    TextView currencySymbolTv2;
    @BindView(R.id.confirmMoneyTv)
    TextView confirmMoneyTv;
    @BindView(R.id.confirmOrderBtn)
    TextView confirmOrderBtn;
    int payMethod = Order.PAY_METHOD_NONE;
    @Autowired
    OrderModel orderModel;
    boolean waitingFinishPay = false;
    //    CreateOrderResponse payResponse = null;
    PingPayModel payResponse = null;
    TrackEvent trackEvent = new TrackEvent();
    BroadcastReceiver broadcastReceiver;
    LoadingDialog waitingFinishPayDialog;


    @BindView(R.id.ll_count)
    LinearLayout ll_count;


    @BindView(R.id.balancePayLayout)
    View balancePayLayout;


    @BindView(R.id.v_balance)
    View vbalance;


    @BindView(R.id.tv_date_info)
    TextView tvDateInfo;

    @BindView(R.id.tv_content_count)
    TextView tvContentCount;

    @BindView(R.id.tv_pay_amount_tag)
    TextView tvPayAmountTag;

    @BindView(R.id.tv_balance_value)
    TextView tvBalanceValue;

    @BindView(R.id.balanceIv)
    ImageView balanceIv;
    @BindView(R.id.tv_balance_tag)
    TextView tvBalanceTag;



    private static final int REQUEST_CODE_PAYMENT = Pingpp.REQUEST_CODE_PAYMENT;

    @Autowired
    public boolean isServiceChargePay; // 是否是手续费支付

    @Autowired
    public UnpayModel unpayModel;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_confirm_pay);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        tvLineationPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中划线
        ll_count.setVisibility(View.GONE);
        tvDateInfo.setVisibility(View.GONE);

        if (isServiceChargePay) {
            titleTv.setText(R.string.pay_refund);
            tvPayAmountTag.setText(getResources().getString(R.string.pay_refund_amount));
        } else {
            titleTv.setText(R.string.confirm_pay);
        }
        if (orderModel == null && unpayModel == null) {
            ToastX.show(R.string.unknown_error);
            finish();
            return;
        }
        waitingFinishPayDialog = LoadingDialog.newBuilder()
                .with(this)
                .message(R.string.text_process)
                .build();
        updateView();
        updatePayTypeView();
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                try {
                    switch (intent.getAction()) {
                        case PayUtil.ACTION_PAY_RESULT: {
                            waitingFinishPayDialog.dismiss();
                            PayResult payResult = PayUtil.obtainPayResult(intent);
                            switch (payResult.getResultCode()) {
                                case PayResult.RESULT_CODE_OK:
                                    paySuccess();
                                    break;
                                case PayResult.RESULT_CODE_FAILED:
                                    payFailed();
                                    break;
                                case PayResult.RESULT_CODE_CANCELED:
                                    repay();
                                    break;
                            }
                            break;
                        }
                    }
                } catch (Exception e) {

                }
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(PayUtil.ACTION_PAY_RESULT);
        registerReceiver(broadcastReceiver, intentFilter);
    }


    private void paySuccess() {
        // 删除掉手续费支付成功的订单
        if (isServiceChargePay && unpayModel != null) {
            PayUtil.removePaidOrder(unpayModel.getId());
        }
        // 手续费支付
        ARouter.getInstance()
                .build(ARouterConfig.PayResultPage)
                .withInt("payResult", PayUtil.PAY_RESULT_SUCCEED)
                .withString("goodsId", isServiceChargePay?unpayModel.getId():orderModel.getGoodsId())
                .withString("orderId", payResponse.getOrderId())
                .withString("sellerPhone", payResponse.getSellerPhone())
                .withBoolean("isServiceChargePay",isServiceChargePay)
                .navigation(ConfirmPayPage.this, REQUEST_CODE_PAY_RESULT);
        setResult(RESULT_OK);
        finish();
    }

    private void payFailed() {
        ARouter.getInstance()
                .build(ARouterConfig.PayResultPage)
                .withInt("payResult", PayUtil.PAY_RESULT_FAILED)
                .withString("goodsId", isServiceChargePay?unpayModel.getId():orderModel.getGoodsId())
                .withString("orderId", payResponse.getOrderId())
                .withString("sellerPhone", payResponse.getSellerPhone())
                .withBoolean("isServiceChargePay",isServiceChargePay)
                .navigation(ConfirmPayPage.this, REQUEST_CODE_PAY_RESULT);
        repay();
    }

    @Override
    protected void onDestroy() {
        try {
            unregisterReceiver(broadcastReceiver);
        } catch (Exception e) {

        }
        super.onDestroy();
    }

    private void clickBackHint() {
        if (isServiceChargePay && unpayModel != null) {
            CommonTitleDetailDialog.newInstance(getString(R.string.pay_service_charge),unpayModel.getRefundFeeDetail(),null,getString(R.string.to_pay)).setListener(new CommonTitleDetailDialog.Listener() {

                @Override
                public void onConfirmClassed() {

                }
            }).show(getSupportFragmentManager(),"");
        }
    }

    public void updateView() {
        if (orderModel != null) {
            Glide.with(this)
                    .load(orderModel.getSellerAvatar())
                    .apply(RequestOptions.placeholderOf(R.drawable.default_head))
                    .apply(RequestOptions.circleCropTransform())
                    .into(avatarIv);
            userNameTv.setText(orderModel.getSellerName());
            Glide.with(this)
                    .load(orderModel.getCoverUrl())
                    .into(coverIv.getImageView());
            goodsTitleTv.setText(orderModel.getTitle());
            singlePriceTv.setText("￥" + StringUtils.priceFormat(orderModel.getSinglePrice()));
            tvLineationPrice.setText("");
            if (!isEmpty(orderModel.getSubject()) && orderModel.getSubject().equals(Subject.major_course)) {
                ll_count.setVisibility(View.VISIBLE);
                goodsBuyNumTv.setText(String.valueOf(orderModel.getBuyNum()));
            }
            switch (orderModel.getSubjectIndex()) {
                case Moment.SUBJECT_VIDEO_COURSE_INDEX:
                    coverIv.setLabel(getString(R.string.learn_video));
                    break;
                case Moment.SUBJECT_MAJOR_COURSE_INDEX:
                    coverIv.setLabel(getString(R.string.major_course));
                    break;
                case Moment.SUBJECT_TRAINING_COURSE_INDEX:
                    coverIv.setLabel(getString(R.string.traing_class));
                    break;
                case Moment.SUBJECT_TRAINING_CARD_INDEX:
                    coverIv.setLabel(getString(R.string.traing_card));
                    break;
                default:
                    coverIv.getLabelTv().setVisibility(View.INVISIBLE);
                    break;
            }
            moneyTv.setText(StringUtils.priceFormat(orderModel.getTotalPrice()));
            confirmMoneyTv.setText(StringUtils.priceFormat(orderModel.getTotalPayPrice()));
            if (!TextUtils.isEmpty(orderModel.getContentCountString())) {
                tvContentCount.setVisibility(View.VISIBLE);
                tvContentCount.setText(orderModel.getContentCountString());
            } else {
                tvContentCount.setVisibility(View.INVISIBLE);
            }
        }

        if (isServiceChargePay && unpayModel != null) {
            vbalance.setVisibility(View.VISIBLE);
            balancePayLayout.setVisibility(View.VISIBLE);
            User user = AccountUtil.getCurrentUser();
            Glide.with(this)
                    .load(user.getAvatar())
                    .apply(RequestOptions.placeholderOf(R.drawable.default_head))
                    .apply(RequestOptions.circleCropTransform())
                    .into(avatarIv);
            userNameTv.setText(user.getAccount());
            Glide.with(this)
                    .load(unpayModel.getCoverUrl())
                    .into(coverIv.getImageView());
            goodsTitleTv.setMaxLines(3);
            goodsTitleTv.setText(unpayModel.getTitle());
            singlePriceTv.setVisibility(View.GONE);
            tvLineationPrice.setVisibility(View.GONE);
            if (!isnEnoughPay()) {
                tvBalanceTag.setTextColor(ContextCompat.getColor(this, R.color.zwcolor_gray_7d8091));
                tvBalanceValue.setText(getString(R.string.balance_not_enough_value, String.valueOf(AccountUtil.getBalance())));
                balanceMethodIv.setImageResource(R.drawable.detail_normal_disable);
                balanceIv.setImageResource(R.drawable.icon_balance_disable);
            } else {
                tvBalanceTag.setTextColor(ContextCompat.getColor(this, R.color.zwcolor_black_111111));
                tvBalanceValue.setText(getString(R.string.balance_value, String.valueOf(AccountUtil.getBalance())));
            }
            ll_count.setVisibility(View.GONE);
            goodsBuyNumTv.setVisibility(View.GONE);
            coverIv.setLabel(Subject.getSubjectName(unpayModel.getSubject()));
            moneyTv.setText(StringUtils.priceFormat(unpayModel.getAmount()));
            confirmMoneyTv.setText(StringUtils.priceFormat(unpayModel.getAmount()));
            tvContentCount.setVisibility(View.INVISIBLE);// 产品说不要这个字段了
        }
    }

    private void requestUnpay() {

    }

    public void updatePayTypeView() {
        switch (payMethod) {
            case Order.PAY_METHOD_ALIPAY_APP:
                balanceMethodIv.setSelected(false);
                alipayMethodIv.setSelected(true);
                wechatMethodIv.setSelected(false);
                break;
            case Order.PAY_METHOD_WECHATPAY_APP:
                balanceMethodIv.setSelected(false);
                alipayMethodIv.setSelected(false);
                wechatMethodIv.setSelected(true);
                break;
            case Order.PAY_METHOD_BALANCE:
                balanceMethodIv.setSelected(true);
                alipayMethodIv.setSelected(false);
                wechatMethodIv.setSelected(false);
                break;
            default:
                balanceMethodIv.setSelected(false);
                alipayMethodIv.setSelected(false);
                wechatMethodIv.setSelected(false);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (isServiceChargePay) {
            clickBackHint();
            return;
        }
        PayUtil.cancelPayDialog(this)
                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ARouter.getInstance()
                                .build(ARouterConfig.MyOrderListPage)
                                .withInt("pageType", MyOrdersDataPage.TYPE_WAITING_PAY_PAGE_1)
                                .navigation(ConfirmPayPage.this);
                        setResult(MOMENT_HAS_CHANGED);
                        finish();
                    }
                })
                .setNegativeButton(R.string.no, null)
                .create()
                .show();
    }

    @OnClick({R.id.balancePayLayout, R.id.wechatPayLayout, R.id.alipayLayout, R.id.titleBackBtn, R.id.confirmOrderBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.balancePayLayout:
                if (isnEnoughPay()) {
                    payMethod = Order.PAY_METHOD_BALANCE;
                    updatePayTypeView();
                }
                break;
            case R.id.wechatPayLayout:
                payMethod = Order.PAY_METHOD_WECHATPAY_APP;
                updatePayTypeView();
                break;
            case R.id.alipayLayout:
                payMethod = Order.PAY_METHOD_ALIPAY_APP;
                updatePayTypeView();
                break;
            case R.id.titleBackBtn:
                onBackPressed();
                break;
            case R.id.confirmOrderBtn:
                doPay();
                break;
        }
    }

    public void doPay() {
        if (payMethod != Order.PAY_METHOD_ALIPAY_APP && payMethod != Order.PAY_METHOD_WECHATPAY_APP && payMethod != Order.PAY_METHOD_BALANCE) {
            ToastX.show(R.string.please_select_pay_method);
        } else if (payMethod == Order.PAY_METHOD_WECHATPAY_APP && !PayUtil.checkWeChatPaySupport()) {
            ToastX.show(R.string.wechat_not_installed);
        }
        else {
            trackEvent.sendEvent(this, TrackEvent.CONFIRM_PAY, TrackEvent.CONFIRM_PAY_LABEL);
            new RequestOrderInfoTask().execute();
        }
    }


    /**
     * 是否可足额支付
     *
     * @return
     */
    private boolean isnEnoughPay() {
        if (isServiceChargePay && unpayModel != null) {
            return (AccountUtil.getBalance() - unpayModel.getAmount()) > 0;
        }
        return false;
    }

    public class RequestOrderInfoTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(ConfirmPayPage.this)
                    .show();

        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Order order = new Order();
                order.setPayMethod(payMethod);
                Response<ResponseBody> response = null;
                if (isServiceChargePay) {
                    response = ApiManager.getService().payRefundOrder(unpayModel.getId(),order).execute();
                } else {
                    response = ApiManager.getService().payOrder(orderModel.getOrderId(), order).execute();
                }
                if (response != null && !response.isSuccessful()) {
                    ErrorResponse errorResponse = ErrorUtil.handleErrorResponse(response);
                    if (errorResponse != null && !TextUtils.isEmpty(errorResponse.getCode())) {
//                        switch (errorResponse.getCode()) {
//                            case ResponseCode.SELL_OUT://#该商品已经售罄！
//                            case ResponseCode.MOMENT_HAS_CHANGED_PLEASE_CREATE_NEW_ORDER://#该商品信息发生变更，请重新下单！
//                            case ResponseCode.CLASS_IS_STARTED://#您购买的课程已经开课，已无法购买！
//                            case ResponseCode.DO_NOT_REPEAT_PAY://重复支付
//                            case ResponseCode.UNDERSTOCK://您购买的商品库存已不足！
//                            case ResponseCode.ORDER_GOODS_IS_EMPTY://#订单中的商品不能为空！
//                            case ResponseCode.DO_NOT_BUY_SELF_GOODS://订单验证失败，卖家不用购买自己的商品{0}！
//                                ToastX.show(errorResponse.getMessage());
//                                throw new BuyException(errorResponse.getCode());
//                            default:
//                                break;
//                        }
                        ToastX.show(errorResponse.getMessage());
                        throw new BuyException(errorResponse.getCode());
                    }

                } else {
                    String json = RetrofitUtil.getResponseBodyAsString(response);
                    payResponse = JsonUtil.toObject(json, PingPayModel.class);
                    if (payResponse == null) {
                        throw new Exception("支付异常");
                    } else {
                        double balance = payResponse.getAvailableBalance();
                        AccountUtil.updateBalance(balance);// 余额发生变更
                    }
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof BuyException) {
                String errorCode = ((Exception) o).getMessage();
                EventBus.getDefault().post(EventMomentChanged.newBuilder().build());
                switch (errorCode) {
                    case ResponseCode.DO_NOT_BUY_SELF_GOODS://订单验证失败，卖家不用购买自己的商品{0}！
                        setResult(REQUEST_CODE_SELL_OUT);// 关闭确认订单页面，从哪来到那去。
                        finish();
                        break;
                    case ResponseCode.ORDER_GOODS_IS_EMPTY://#订单中的商品不能为空！
                        setResult(ORDER_GOODS_IS_EMPTY);// 关闭确认订单页面，从哪来到那去。
                        finish();
                        break;
                    case ResponseCode.UNDERSTOCK://您购买的商品库存已不足！
                        setResult(REQUEST_CODE_SELL_OUT);// 关闭支付页面，刷新订单确认页。
                        finish();
                        break;
                    case ResponseCode.DO_NOT_REPEAT_PAY://重复支付
                        setResult(REQUEST_CODE_CONFIRM_PAY);// 关闭确认订单页面，从哪来到那去。
                        EventBus.getDefault().post(EventMomentChanged.newBuilder().build());
                        finish();
                        break;
                    case ResponseCode.CLASS_IS_STARTED://#您购买的课程已经开课，已无法购买！
                        setResult(CLASS_IS_STARTED);// 关闭确认订单页面，从哪来到那去。
                        finish();
                        break;
                    case ResponseCode.MOMENT_HAS_CHANGED_PLEASE_CREATE_NEW_ORDER://#该商品信息发生变更，请重新下单！
                        setResult(MOMENT_HAS_CHANGED);// 关闭支付页面，刷新订单确认页。

                        finish();
                        break;
                    case ResponseCode.SELL_OUT://#该商品已经售罄！
                        setResult(REQUEST_CODE_SELL_OUT);// 关闭确认订单页面，从哪来到那去。
                        finish();
                        break;
                }

            } else if (o instanceof RepeatBuyException) {
                PayUtil.repeatPayAlertDialog(ConfirmPayPage.this)
                        .setPositiveButton(R.string.view_goods, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ConfirmPayPage.this.finish();
                                ARouter.getInstance()
                                        .build(ARouterConfig.MyBuyPage)
                                        .navigation();
                            }
                        })
                        .setNegativeButton(R.string.back_to_order, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ConfirmPayPage.this.finish();
                                ARouter.getInstance()
                                        .build(ARouterConfig.MyOrderListPage)
                                        .navigation();
                            }
                        })
                        .create()
                        .show();
            } else if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                waitingFinishPay();
                if (payResponse == null) {
                    ToastX.show("支付异常,请稍后重试");
                    repay();
                    return;
                }
                if (payResponse.isPayed()) {
                    paySuccess();
                    return;
                }
                if (!TextUtils.isEmpty(payResponse.getPingPayOrder())) {
                    Pingpp.createPayment(ConfirmPayPage.this, payResponse.getPingPayOrder());
                }

            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (waitingFinishPay) {
            waitingFinishPay = false;
//            if (payMethod != Order.PAY_METHOD_WECHATPAY_APP) {
//                checkPayResult();
//            }
            checkPayResult();
        }
    }

    public void waitingFinishPay() {
        confirmOrderBtn.setClickable(false);
        waitingFinishPay = true;
        confirmOrderBtn.setText(R.string.waiting_finish_pay);
    }

    public void checkPayResult() {
//        confirmOrderBtn.setText(R.string.checking_pay_result);
        new CheckPayResultTask().execute();
    }

    public class CheckPayResultTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(ConfirmPayPage.this)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService()
                        .checkPayResult(payResponse.getOrderCode())
                        .execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                OrderPay orderPay = JSON.parseObject(json, OrderPay.class);
                if (orderPay == null) {
                    throw new Exception("支付异常");
                }
                return orderPay;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            int payResult;
            if (o instanceof Exception) {
                payResult = PayUtil.PAY_RESULT_FAILED;
            } else {
                OrderPay orderPay = (OrderPay) o;
                switch (orderPay.getStatus()) {
                    case OrderPay.STATUS_PAY_SUCCEED:
                        payResult = PayUtil.PAY_RESULT_SUCCEED;
                        break;
                    default:
                        payResult = PayUtil.PAY_RESULT_FAILED;
                        break;
                }
            }

            if (payResult == PayUtil.PAY_RESULT_SUCCEED) {
                paySuccess();
            } else if (payResult == PayUtil.PAY_RESULT_FAILED) {
                payFailed();
            } else {
                payFailed();
            }
        }
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        switch (requestCode) {
//            case REQUEST_CODE_PAY_RESULT:
//                if (resultCode == RESULT_CANCELED) {
//                    setResult(RESULT_OK);
//                    finish();
//                } else {
//                    repay();
//                }
//                break;
//            default:
//                super.onActivityResult(requestCode, resultCode, data);
//                break;
//        }
//    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_PAY_RESULT: {
                if (resultCode == RESULT_CANCELED) {
                    repay();
                }
                break;
            }
            case 1010: {// PING++ result
                String result = data.getExtras().getString("pay_result");
                /* 处理返回值
                 * "success" - 支付成功
                 * "fail"    - 支付失败
                 * "cancel"  - 取消支付
                 * "invalid" - 支付插件未安装（一般是微信客户端未安装的情况）
                 * "unknown" - app进程异常被杀死(一般是低内存状态下,app进程被杀死)
                 */
                if (!TextUtils.isEmpty(result) && result.equals("success")) {
                    paySuccess();

                } else {
                    repay();
                }
                String errorMsg = data.getExtras().getString("error_msg"); // 错误信息
                String extraMsg = data.getExtras().getString("extra_msg"); // 错误信息
                if (!TextUtils.isEmpty(errorMsg)) {
                    CrashUtils.getInstance().netSubmitLog(AiyigeExceptionModel.type_pay_error, "支付error_msg：" + errorMsg + "\nextra_msg：" + extraMsg + "\norderModel的值：" +
                            (isServiceChargePay && unpayModel != null ?unpayModel.toString():orderModel.toString())
                            + "\n支付信息" + payResponse.getPingPayOrder(), AiyigeExceptionModel.rating_4);
                }
                break;
            }

            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }

// 注：线下渠道无支付结果返回, 返回 unknown 字段。需要从服务端获取正确的支付结果。

    public void repay() {
        confirmOrderBtn.setClickable(true);
        confirmOrderBtn.setText(R.string.confirm_pay_label);
    }


    public class RepeatBuyException extends Exception {
        public RepeatBuyException(String message) {
            super(message);
        }
    }

    public class BuyException extends Exception {
        public BuyException(String message) {
            super(message);
        }
    }
}
